// ==UserScript==
// @name         小红书评论地理位置过滤器
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  根据地理位置过滤小红书评论，支持省份筛选
// @author       Assistant
// @match        *://*.xiaohongshu.com/*
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_addStyle
// @run-at       document-start
// ==/UserScript==

(function() {
    'use strict';
    
    console.log('🔧 小红书地理位置过滤器脚本开始执行');

    // 省份映射表（标准化不同显示格式）
    const PROVINCE_MAP = {
        "北京": "北京市",
        "上海": "上海市", 
        "天津": "天津市",
        "重庆": "重庆市",
        "河北": "河北省",
        "山西": "山西省",
        "辽宁": "辽宁省",
        "吉林": "吉林省",
        "黑龙江": "黑龙江省",
        "江苏": "江苏省",
        "浙江": "浙江省",
        "安徽": "安徽省",
        "福建": "福建省",
        "江西": "江西省",
        "山东": "山东省",
        "河南": "河南省",
        "湖北": "湖北省",
        "湖南": "湖南省",
        "广东": "广东省",
        "广西": "广西壮族自治区",
        "海南": "海南省",
        "四川": "四川省",
        "贵州": "贵州省",
        "云南": "云南省",
        "西藏": "西藏自治区",
        "陕西": "陕西省",
        "甘肃": "甘肃省",
        "青海": "青海省",
        "宁夏": "宁夏回族自治区",
        "新疆": "新疆维吾尔自治区",
        "内蒙古": "内蒙古自治区",
        "台湾": "台湾省",
        "香港": "香港特别行政区",
        "澳门": "澳门特别行政区"
    };

    // 热门省份列表
    const HOT_PROVINCES = ["北京", "上海", "广东", "浙江", "江苏", "山东", "河南", "四川", "湖北", "湖南"];

    // 配置管理
    class ConfigManager {
        constructor() {
            this.defaultConfig = {
                mode: "include", // include | exclude
                provinces: [],
                enabled: true,
                filterByIpLocation: true,
                showStats: true
            };
        }

        load() {
            const savedConfig = GM_getValue('xhs_location_filter_config', null);
            return savedConfig ? {...this.defaultConfig, ...JSON.parse(savedConfig)} : this.defaultConfig;
        }

        save(config) {
            GM_setValue('xhs_location_filter_config', JSON.stringify(config));
        }
    }

    // 地理位置解析器
    class LocationParser {
        static parseLocation(commentElement) {
            try {
                // 查找地理位置标签（通常在用户信息区域）
                const locationElement = commentElement.querySelector('[class*="location"], [class*="ip"], [class*="地区"], [class*="province"]');
                
                if (locationElement) {
                    const locationText = locationElement.textContent.trim();
                    return this.normalizeProvince(locationText);
                }

                // 备用方案：查找包含地理位置信息的文本
                const textNodes = this.getTextNodes(commentElement);
                for (const node of textNodes) {
                    const text = node.textContent.trim();
                    const matchedProvince = this.extractProvinceFromText(text);
                    if (matchedProvince) {
                        return matchedProvince;
                    }
                }

                return null;
            } catch (error) {
                console.warn('解析地理位置时出错:', error);
                return null;
            }
        }

        static getTextNodes(element) {
            const textNodes = [];
            const walker = document.createTreeWalker(
                element,
                NodeFilter.SHOW_TEXT,
                null,
                false
            );

            let node;
            while (node = walker.nextNode()) {
                if (node.textContent.trim()) {
                    textNodes.push(node);
                }
            }
            return textNodes;
        }

        static extractProvinceFromText(text) {
            for (const [shortName, fullName] of Object.entries(PROVINCE_MAP)) {
                if (text.includes(shortName) || text.includes(fullName)) {
                    return shortName;
                }
            }
            return null;
        }

        static normalizeProvince(locationText) {
            // 移除可能的标点符号和空格
            const cleanText = locationText.replace(/[·\s\-·]/g, '');
            
            // 直接匹配省份名称
            for (const [shortName, fullName] of Object.entries(PROVINCE_MAP)) {
                if (cleanText.includes(shortName) || cleanText.includes(fullName)) {
                    return shortName;
                }
            }
            return cleanText; // 如果无法映射，返回原始文本
        }
    }

    // 评论过滤器
    class CommentFilter {
        constructor(config) {
            this.config = config;
            this.stats = new Map(); // 省份统计
            this.totalComments = 0;
            this.visibleComments = 0;
        }

        updateConfig(newConfig) {
            this.config = {...this.config, ...newConfig};
        }

        shouldShowComment(commentElement) {
            if (!this.config.enabled) return true;
            if (this.config.provinces.length === 0) return true;

            const location = LocationParser.parseLocation(commentElement);
            if (!location) return true; // 无法识别位置的评论默认显示

            // 更新统计
            this.stats.set(location, (this.stats.get(location) || 0) + 1);

            const isInSelectedProvinces = this.config.provinces.includes(location);

            if (this.config.mode === "include") {
                return isInSelectedProvinces;
            } else {
                return !isInSelectedProvinces;
            }
        }

        filterComments() {
            // 查找评论容器 - 基于常见的小红书评论区域选择器
            const commentSelectors = [
                '.comment-list',
                '.comments-container', 
                '.comment-wrapper',
                '[class*="comment"]',
                '.note-item .footer',
                '.interaction'
            ];

            let commentContainer = null;
            for (const selector of commentSelectors) {
                commentContainer = document.querySelector(selector);
                if (commentContainer) break;
            }

            if (!commentContainer) {
                console.warn('未找到评论容器');
                return;
            }

            // 查找评论元素
            const commentElements = commentContainer.querySelectorAll('[class*="comment-item"], [class*="comment"], .note-item, [class*="interaction"]');
            
            this.totalComments = commentElements.length;
            this.visibleComments = 0;
            this.stats.clear();

            commentElements.forEach(comment => {
                const shouldShow = this.shouldShowComment(comment);
                
                if (shouldShow) {
                    comment.style.display = '';
                    this.visibleComments++;
                } else {
                    comment.style.display = 'none';
                }
            });

            // 更新统计显示
            this.updateStatsDisplay();
        }

        updateStatsDisplay() {
            const statsElement = document.getElementById('xhs-location-stats');
            if (statsElement && this.config.showStats) {
                const statsText = `显示 ${this.visibleComments}/${this.totalComments} 条评论`;
                const provinceStats = Array.from(this.stats.entries())
                    .sort((a, b) => b[1] - a[1])
                    .slice(0, 5)
                    .map(([province, count]) => `${province}: ${count}`)
                    .join(' | ');
                
                statsElement.innerHTML = `${statsText}<br><small>${provinceStats}</small>`;
            }
        }

        resetFilter() {
            const commentElements = document.querySelectorAll('[class*="comment-item"], [class*="comment"], .note-item, [class*="interaction"]');
            commentElements.forEach(comment => {
                comment.style.display = '';
            });
            this.visibleComments = this.totalComments;
            this.stats.clear();
            this.updateStatsDisplay();
        }
    }

    // UI管理器
    class UIManager {
        constructor(filter, configManager) {
            this.filter = filter;
            this.configManager = configManager;
            this.config = configManager.load();
            this.selectedProvinces = new Set(this.config.provinces);
        }

                 createFilterPanel() {
             console.log('🎨 UIManager.createFilterPanel() 开始创建面板');
             
             // 检查是否已存在面板
             const existingPanel = document.querySelector('.xhs-location-filter');
             if (existingPanel) {
                 console.log('⚠️ 过滤面板已存在，移除旧面板');
                 existingPanel.remove();
             }
             
             // 添加样式
             console.log('🎨 添加CSS样式');
             GM_addStyle(`
                .xhs-location-filter {
                    position: fixed;
                    top: 20px;
                    right: 20px;
                    width: 320px;
                    background: #fff;
                    border: 1px solid #e5e5e5;
                    border-radius: 8px;
                    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
                    z-index: 10000;
                    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif;
                    font-size: 14px;
                    color: #000;
                }
                
                .xhs-filter-header {
                    padding: 12px 16px;
                    border-bottom: 1px solid #f0f0f0;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    background: #ff2442;
                    color: white;
                    border-radius: 8px 8px 0 0;
                    font-weight: 500;
                }
                
                .xhs-filter-toggle {
                    background: none;
                    border: none;
                    color: white;
                    cursor: pointer;
                    font-size: 16px;
                }
                
                .xhs-filter-content {
                    padding: 16px;
                    max-height: 400px;
                    overflow-y: auto;
                }
                
                .xhs-filter-section {
                    margin-bottom: 16px;
                }
                
                .xhs-filter-label {
                    display: block;
                    margin-bottom: 8px;
                    font-weight: 500;
                    color: #000;
                }
                
                .xhs-mode-switch {
                    display: flex;
                    margin-bottom: 12px;
                }
                
                .xhs-mode-btn {
                    flex: 1;
                    padding: 6px 12px;
                    border: 1px solid #ff2442;
                    background: white;
                    color: #ff2442;
                    cursor: pointer;
                    transition: all 0.2s;
                }
                
                .xhs-mode-btn:first-child {
                    border-radius: 4px 0 0 4px;
                }
                
                .xhs-mode-btn:last-child {
                    border-radius: 0 4px 4px 0;
                    border-left: none;
                }
                
                .xhs-mode-btn.active {
                    background: #ff2442;
                    color: white;
                }
                
                .xhs-province-search {
                    width: 100%;
                    padding: 8px 12px;
                    border: 1px solid #ddd;
                    border-radius: 4px;
                    margin-bottom: 8px;
                }
                
                .xhs-hot-provinces {
                    display: flex;
                    flex-wrap: wrap;
                    gap: 4px;
                    margin-bottom: 12px;
                }
                
                .xhs-province-tag {
                    padding: 4px 8px;
                    background: #f5f5f5;
                    border: 1px solid #ddd;
                    border-radius: 12px;
                    cursor: pointer;
                    font-size: 12px;
                    transition: all 0.2s;
                }
                
                .xhs-province-tag:hover {
                    background: #ff2442;
                    color: white;
                    border-color: #ff2442;
                }
                
                .xhs-province-tag.selected {
                    background: #ff2442;
                    color: white;
                    border-color: #ff2442;
                }
                
                .xhs-selected-provinces {
                    min-height: 24px;
                    padding: 8px;
                    background: #f9f9f9;
                    border-radius: 4px;
                    margin-bottom: 12px;
                }
                
                .xhs-selected-tag {
                    display: inline-block;
                    padding: 2px 8px;
                    margin: 2px;
                    background: #ff2442;
                    color: white;
                    border-radius: 12px;
                    font-size: 12px;
                }
                
                .xhs-remove-tag {
                    margin-left: 4px;
                    cursor: pointer;
                    font-weight: bold;
                }
                
                .xhs-action-buttons {
                    display: flex;
                    gap: 8px;
                }
                
                .xhs-btn {
                    flex: 1;
                    padding: 8px 16px;
                    border: 1px solid #ff2442;
                    border-radius: 4px;
                    cursor: pointer;
                    transition: all 0.2s;
                    text-align: center;
                }
                
                .xhs-btn-primary {
                    background: #ff2442;
                    color: white;
                }
                
                .xhs-btn-secondary {
                    background: white;
                    color: #ff2442;
                }
                
                .xhs-btn:hover {
                    opacity: 0.8;
                }
                
                .xhs-stats {
                    margin-top: 12px;
                    padding: 8px;
                    background: #f0f8ff;
                    border-radius: 4px;
                    font-size: 12px;
                    color: #000;
                }
                
                .xhs-filter-collapsed .xhs-filter-content {
                    display: none;
                }
            `);

            // 创建过滤面板
            const panel = document.createElement('div');
            panel.className = 'xhs-location-filter';
            panel.innerHTML = `
                <div class="xhs-filter-header">
                    <span>地理位置过滤</span>
                    <button class="xhs-filter-toggle">−</button>
                </div>
                <div class="xhs-filter-content">
                    <div class="xhs-filter-section">
                        <label class="xhs-filter-label">过滤模式</label>
                        <div class="xhs-mode-switch">
                            <button class="xhs-mode-btn ${this.config.mode === 'include' ? 'active' : ''}" data-mode="include">仅显示</button>
                            <button class="xhs-mode-btn ${this.config.mode === 'exclude' ? 'active' : ''}" data-mode="exclude">排除</button>
                        </div>
                    </div>
                    
                    <div class="xhs-filter-section">
                        <label class="xhs-filter-label">省份搜索</label>
                        <input type="text" class="xhs-province-search" placeholder="输入省份名称...">
                    </div>
                    
                    <div class="xhs-filter-section">
                        <label class="xhs-filter-label">热门省份</label>
                        <div class="xhs-hot-provinces">
                            ${HOT_PROVINCES.map(province => 
                                `<span class="xhs-province-tag ${this.selectedProvinces.has(province) ? 'selected' : ''}" data-province="${province}">${province}</span>`
                            ).join('')}
                        </div>
                    </div>
                    
                    <div class="xhs-filter-section">
                        <label class="xhs-filter-label">已选择省份</label>
                        <div class="xhs-selected-provinces" id="xhs-selected-display">
                            ${Array.from(this.selectedProvinces).map(province => 
                                `<span class="xhs-selected-tag">${province}<span class="xhs-remove-tag" data-province="${province}">×</span></span>`
                            ).join('')}
                        </div>
                    </div>
                    
                    <div class="xhs-action-buttons">
                        <button class="xhs-btn xhs-btn-primary" id="xhs-apply-filter">应用过滤</button>
                        <button class="xhs-btn xhs-btn-secondary" id="xhs-reset-filter">重置</button>
                    </div>
                    
                    <div class="xhs-stats" id="xhs-location-stats">
                        等待过滤...
                    </div>
                </div>
            `;

                         console.log('📍 将面板添加到页面body');
             document.body.appendChild(panel);
             console.log('✅ 面板已添加到DOM');
             
             console.log('🔗 绑定事件监听器');
             this.bindEvents(panel);
             console.log('✅ 事件绑定完成');
             
             return panel;
        }

        bindEvents(panel) {
            // 折叠/展开
            const toggleBtn = panel.querySelector('.xhs-filter-toggle');
            toggleBtn.addEventListener('click', () => {
                panel.classList.toggle('xhs-filter-collapsed');
                toggleBtn.textContent = panel.classList.contains('xhs-filter-collapsed') ? '+' : '−';
            });

            // 模式切换
            const modeButtons = panel.querySelectorAll('.xhs-mode-btn');
            modeButtons.forEach(btn => {
                btn.addEventListener('click', () => {
                    modeButtons.forEach(b => b.classList.remove('active'));
                    btn.classList.add('active');
                    this.config.mode = btn.dataset.mode;
                    this.configManager.save(this.config);
                });
            });

            // 省份搜索
            const searchInput = panel.querySelector('.xhs-province-search');
            searchInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    const province = this.findMatchingProvince(e.target.value.trim());
                    if (province && !this.selectedProvinces.has(province)) {
                        this.addProvince(province);
                        e.target.value = '';
                    }
                }
            });

            // 热门省份点击
            const provinceTagsContainer = panel.querySelector('.xhs-hot-provinces');
            provinceTagsContainer.addEventListener('click', (e) => {
                if (e.target.classList.contains('xhs-province-tag')) {
                    const province = e.target.dataset.province;
                    if (this.selectedProvinces.has(province)) {
                        this.removeProvince(province);
                    } else {
                        this.addProvince(province);
                    }
                }
            });

            // 移除已选择的省份
            const selectedDisplay = panel.querySelector('#xhs-selected-display');
            selectedDisplay.addEventListener('click', (e) => {
                if (e.target.classList.contains('xhs-remove-tag')) {
                    const province = e.target.dataset.province;
                    this.removeProvince(province);
                }
            });

            // 应用过滤
            panel.querySelector('#xhs-apply-filter').addEventListener('click', () => {
                this.config.provinces = Array.from(this.selectedProvinces);
                this.configManager.save(this.config);
                this.filter.updateConfig(this.config);
                this.filter.filterComments();
            });

            // 重置过滤
            panel.querySelector('#xhs-reset-filter').addEventListener('click', () => {
                this.selectedProvinces.clear();
                this.config.provinces = [];
                this.configManager.save(this.config);
                this.filter.updateConfig(this.config);
                this.filter.resetFilter();
                this.updateSelectedDisplay();
                this.updateHotProvincesTags();
            });
        }

        findMatchingProvince(input) {
            for (const [shortName, fullName] of Object.entries(PROVINCE_MAP)) {
                if (shortName.includes(input) || fullName.includes(input) || input.includes(shortName)) {
                    return shortName;
                }
            }
            return null;
        }

        addProvince(province) {
            this.selectedProvinces.add(province);
            this.updateSelectedDisplay();
            this.updateHotProvincesTags();
        }

        removeProvince(province) {
            this.selectedProvinces.delete(province);
            this.updateSelectedDisplay();
            this.updateHotProvincesTags();
        }

        updateSelectedDisplay() {
            const display = document.getElementById('xhs-selected-display');
            if (display) {
                display.innerHTML = Array.from(this.selectedProvinces).map(province => 
                    `<span class="xhs-selected-tag">${province}<span class="xhs-remove-tag" data-province="${province}">×</span></span>`
                ).join('');
            }
        }

        updateHotProvincesTags() {
            const tags = document.querySelectorAll('.xhs-province-tag');
            tags.forEach(tag => {
                const province = tag.dataset.province;
                if (this.selectedProvinces.has(province)) {
                    tag.classList.add('selected');
                } else {
                    tag.classList.remove('selected');
                }
            });
        }
    }

    // 主程序
    class XHSLocationFilter {
        constructor() {
            this.configManager = new ConfigManager();
            this.config = this.configManager.load();
            this.filter = new CommentFilter(this.config);
            this.uiManager = new UIManager(this.filter, this.configManager);
            this.observer = null;
        }

        init() {
            console.log('🚀 XHSLocationFilter.init() 调用');
            console.log('📍 当前页面URL:', window.location.href);
            console.log('📄 当前document.readyState:', document.readyState);
            
            // 等待页面加载完成
            if (document.readyState === 'loading') {
                console.log('⏳ 页面正在加载，等待DOMContentLoaded事件');
                document.addEventListener('DOMContentLoaded', () => this.start());
            } else {
                console.log('✅ 页面已加载完成，1秒后启动过滤器');
                setTimeout(() => this.start(), 1000);
            }
        }

        start() {
            console.log('🎯 小红书地理位置过滤器启动');
            console.log('⚙️ 当前配置:', this.config);
            
            try {
                // 创建UI
                console.log('🎨 开始创建过滤面板UI');
                const panel = this.uiManager.createFilterPanel();
                console.log('✅ 过滤面板UI创建完成:', panel);
                
                // 添加临时提示确保脚本正在工作
                const testAlert = document.createElement('div');
                testAlert.style.cssText = `
                    position: fixed;
                    top: 10px;
                    left: 10px;
                    background: #ff2442;
                    color: white;
                    padding: 10px;
                    border-radius: 5px;
                    z-index: 99999;
                    font-size: 14px;
                    font-family: Arial, sans-serif;
                `;
                testAlert.textContent = '✅ 小红书过滤器已加载！';
                document.body.appendChild(testAlert);
                setTimeout(() => testAlert.remove(), 3000);
                console.log('🎉 显示加载成功提示');
                
                // 监听DOM变化（小红书是SPA，内容动态加载）
                console.log('👁️ 开始监听DOM变化');
                this.observeChanges();
                
                // 初始过滤
                if (this.config.enabled && this.config.provinces.length > 0) {
                    console.log('🔍 配置启用且有省份选择，2秒后开始初始过滤');
                    setTimeout(() => this.filter.filterComments(), 2000);
                } else {
                    console.log('ℹ️ 过滤器未启用或无省份选择，跳过初始过滤');
                }
            } catch (error) {
                console.error('❌ 启动过滤器时出错:', error);
            }
        }

        observeChanges() {
            const targetNode = document.body;
            const config = { 
                childList: true, 
                subtree: true,
                attributes: true
            };

            this.observer = new MutationObserver((mutations) => {
                let shouldRefilter = false;
                
                mutations.forEach((mutation) => {
                    if (mutation.type === 'childList') {
                        // 检查是否有新的评论元素添加
                        mutation.addedNodes.forEach((node) => {
                            if (node.nodeType === Node.ELEMENT_NODE) {
                                if (node.matches && (
                                    node.matches('[class*="comment"]') || 
                                    node.matches('.note-item') ||
                                    node.querySelector('[class*="comment"], .note-item')
                                )) {
                                    shouldRefilter = true;
                                }
                            }
                        });
                    }
                });

                if (shouldRefilter && this.config.enabled && this.config.provinces.length > 0) {
                    // 防抖：避免频繁重新过滤
                    clearTimeout(this.refilterTimeout);
                    this.refilterTimeout = setTimeout(() => {
                        this.filter.filterComments();
                    }, 500);
                }
            });

            this.observer.observe(targetNode, config);
        }

        destroy() {
            if (this.observer) {
                this.observer.disconnect();
            }
            const panel = document.querySelector('.xhs-location-filter');
            if (panel) {
                panel.remove();
            }
        }
    }

    // 启动过滤器
    console.log('🏁 准备启动过滤器实例');
    const locationFilter = new XHSLocationFilter();
    console.log('🏁 过滤器实例创建完成，开始初始化');
    locationFilter.init();

    // 在页面卸载时清理
    window.addEventListener('beforeunload', () => {
        locationFilter.destroy();
    });

})();
